package org.example.filter;

import com.alibaba.fastjson.JSON;
import org.example.entity.User;
import org.example.other.ErrorEnum;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebFilter(urlPatterns = "/*")
public class LoginFilter extends HttpFilter {
    // 放行的地址集合
    static final List<String> RELEASE_ADDRESS_LIST = new ArrayList<String>();

    // 初始化需要被放行的地址
    static {
        RELEASE_ADDRESS_LIST.add("/user/login");
    }

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        res.setCharacterEncoding("utf-8");
        String method = req.getMethod();
        if ("OPTIONS".equals(method)) {
            chain.doFilter(req, res);
            return;
        }
        // 获取一下本次请求的URI
        String requestURI = req.getRequestURI();
        // 判断本次请求的URI是不是"/login", 如果是, 则说明本次请求是一个登录请求
        if (RELEASE_ADDRESS_LIST.contains(requestURI)) {
            // 直接放行
            chain.doFilter(req, res);
            // 后面不执行, 此处return指的过滤器return了, 请求放行到servlet继续执行
            return;
        }
        // 获取到用户的session对象 (用户私有的储物柜, session也是k-v结构)
        HttpSession session = req.getSession();
        // 从session对象中取出user对象
        User user = (User)session.getAttribute("user");
        // 1. 没有登录 (我们会在用户登录成功后在他的session对象中设置登录状态)
        // 2. session过期了, 自动刷新session, 状态丢失
        if (user == null) {
            Map map = new HashMap();
            map.put("code", ErrorEnum.LOGIN_EXPIRATION.getCode());
            map.put("message", ErrorEnum.LOGIN_EXPIRATION.getMessage());
            res.setContentType("application/json;charset=utf-8");
            PrintWriter out = res.getWriter();
            out.write(JSON.toJSONString(map));
            out.flush();
            out.close();
        } else {
            // 放行
            chain.doFilter(req,res);
        }
    }
}
